import Basic from './Basic';
import path from 'path';
import config from './config';
import fs from 'fs';
import glob from 'glob';
import ejs from 'ejs';
import stream from 'stream';
import shelljs from 'shelljs';

class Component extends Basic {
    constructor(args) {
        super(args);
        // code
        this.root = path.dirname(path.dirname(__dirname));
        this.config = config;
        this.targetDir = '';
        this.tplDir = '';
        this.type = '';

        ejs.delimiter = '?';


    }
    // methods
    create({ componentName }) {

        // 1. read template string and render it;

        // 2. write render result to target file;

        let tpls = glob.sync(`${this.tplDir}/*.*`);

        tpls.map(tplFile => new Promise((r, j) => {

            let data = {
                className: `orin-${this.type}-${componentName.toLowerCase()}-root`,
                componentName,
                coreLess: '',
            };
            let filename = tplFile.split('/').pop();
            if (tplFile.split('.').pop() == 'less') {
                data.coreLess = this.compareDir(this.root + this.config.coreLess, `${this.targetDir}/${componentName}/index.less`);
            }



            let str = ejs.render(fs.readFileSync(tplFile, 'utf8'), { orin: data });

            //if (tplFile.split('.').pop() == 'less') console.log(str);
            this.write(null, str, `${this.targetDir}/${componentName}/${filename}`);

        }));


        return true;

    }

    remove({ componentName }) {
        //console.log(`${this.targetDir}/${componentName}`);
        shelljs.rm('-r', `${this.targetDir}/${componentName}`);
        return true;
    }

    write(fromFilePath, withData, toFilePath) {

        var readable = new stream.Readable;
        if (!fs.existsSync(toFilePath)) {

            let toFilePathDir = toFilePath.split('/');
            toFilePathDir.pop();
            toFilePathDir = toFilePathDir.join('/');

            shelljs.mkdir('-p', toFilePathDir);
        }
        var writable = fs.createWriteStream(toFilePath);

        if (fromFilePath) {
            readable = fs.createReadStream(fromFilePath);
        } else {
            readable._read = () => {};
        }

        if (withData) {

            readable.push(withData);
        }

        readable.pipe(writable);

        return this;
    }

    compareDir(beComparedFile, file) {

        var fArr = file.split('/');
        var beArr = beComparedFile.split('/');
        fArr.shift();
        beArr.shift();

        while (fArr && beArr && fArr[0] == beArr[0]) {
            fArr.shift();
            beArr.shift();
        }

        if (fArr.length > 1) {
            return new Array(fArr.length).join('../') + beArr.join('/');
        } else {
            return false;
        }

    }

    update() {

    }

}

export default Component;